<template>
  <div class="object-display border rounded-md p-4 bg-white">
    <div class="flex items-center justify-between mb-2">
      <div class="flex items-center">
        <i class="fa fa-object-group text-primary mr-2"></i>
        <span class="font-medium">对象</span>
        <span class="ml-2 text-sm text-gray-500">({{ getPropertyCount() }} 个属性)</span>
      </div>
      <button 
        class="edit-button px-3 py-1 bg-primary text-white text-sm rounded hover:bg-primary/90 transition-colors flex items-center"
        @click="onEdit"
      >
        <i class="fa fa-pencil mr-1"></i> 编辑
      </button>
    </div>

    <!-- 显示前两个属性的预览 -->
    <div class="properties-preview text-sm text-gray-600 bg-gray-50 p-3 rounded-md">
      <template v-if="value && Object.keys(value).length > 0">
        <span v-for="(key, i) in Object.keys(value).slice(0, 2)" :key="i">
          {{ key }}: {{ formatValue(value[key]) }}
          <span v-if="i < 1 && Object.keys(value).length > 1">, </span>
        </span>
        <span v-if="Object.keys(value).length > 2">...</span>
      </template>
      <template v-else>
        <span class="text-gray-400 italic">空对象</span>
      </template>
    </div>
  </div>
</template>

<script>
// 格式化值用于预览
const formatValue = (value) => {
  if (typeof value === 'string') {
    return `"${value.length > 15 ? value.slice(0, 15) + '...' : value}"`;
  }
  if (typeof value === 'object' && value !== null) {
    return Array.isArray(value) ? `[${value.length}项]` : '{对象}';
  }
  return String(value);
};

export default {
  props: {
    value: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['edit'],
  setup(props, { emit }) {
    // 获取属性数量
    const getPropertyCount = (obj = props.value) => {
      return obj ? Object.keys(obj).length : 0;
    };

    // 触发编辑事件
    const onEdit = () => {
      emit('edit');
    };

    return {
      formatValue,
      getPropertyCount,
      onEdit
    };
  }
};
</script>

<style scoped>
.object-display {
  width: 100%;
  border: 1px solid #e5e7eb;
  margin-bottom: 10px;
  transition: all 0.2s ease;
}

.object-display:hover {
  border-color: #94bfff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.edit-button {
  white-space: nowrap;
}

.properties-preview {
  word-break: break-all;
  transition: all 0.2s ease;
}
</style>